import {handler, view, BondViewGroup} from "adajs";
import LodgeService from "./state.js";
import Bar from "../../../controls/bar";
import Form from "./../../../controls/form";
import Toast from "./../../../controls/toast";
import Loading from "./../../../controls/loading";
import User from "./../../../lib/user";

@view({
    className: "lodge",
    template: "./template.html",
    style: "./style.scss",
    dataset: {
        service: LodgeService
    }
})
class Lodge extends BondViewGroup {
    tags() {
        return {
            bar: Bar,
            form: Form
        }
    }

    @handler("bar-add")
    barAdd({data}) {
        console.log(data);
    }

    @handler("submit")
    submit() {
        let form = this.getChildrenByType(Form)[0];
        form.check().then(result => {
            if (result) {
                form.getValue().then(values => {
                    console.log(values);
                    let back = values.backDate, go = values.goDate;
                    if (new Date(`${back.replace(/-/g, "/")} 0:0:0`).getTime() < new Date(`${go.replace(/-/g, "/")} 0:0:0`).getTime()) {
                        this.addChild(Toast, {
                            parameter: {content: "返回日期不能早于出发日期"}
                        });
                    } else {
                        this.addChild(Loading).then(loading => {
                            let t = new Date();
                            if(!User.isAdmin()) {
                                values.sqrid = User.getUserInfo().id;
                            }
                            values.applyTime = `${t.getFullYear()}-${t.getMonth() + 1}-${t.getDate()}`;
                            this.context.request.post("/api/lgb/app/lgb/abroad/insert", values).then(info => {
                                if (info.code === "1") {
                                    loading.showSuccess("申请成功");
                                    loading.close().then(() => {
                                        window.history.back();
                                    });
                                } else {
                                    loading.showSuccess(info.msg);
                                    loading.close()
                                }
                            });
                        });
                    }
                });
            }
        });
    }
}

export default Lodge;